package 字符串;

/**
 * @Author Weton Li
 * @Date 2021/4/25 09:11
 */
public class 罗马数字 {
    public static void main(String[] args) {
//        String input = "VII";
//        String input = "IV";
        String input = "DCXXI"; // 500+100+20+1=621
        System.out.println(method(input));
    }
    public static int romanToInt(String s) {

        int left = 0,leftVal,right = 1,rightVal,len=s.length(),sum=0;
        char leftChar,rightChar;
        if (s.length()==1){
            return getValue(s.charAt(0));
        }
        while(right<len){
            leftChar = s.charAt(left);
            rightChar = s.charAt(right);
            leftVal = getValue(leftChar);
            rightVal = getValue(rightChar);
            if (leftVal < rightVal){
                sum += rightVal;
                sum -= leftVal;
                left  += 2;
                right += 2;
            }else {
                sum += leftVal;
                left++;
                right++;
            }
        }
        if (right == len){
            sum += getValue(s.charAt(left));
        }
        return sum;
    }

    
    public static int method(String s){
        
        int left = 0;
        int right = 1;
        int leftVal = 0;
        int rightVal = 0;

        char leftChar;
        char rightChar;
        int sum = 0;

        if (s.length() == 1) {
            return getValue(s.charAt(0));
        }
        while (right<s.length()){
            leftChar = s.charAt(left);
            rightChar = s.charAt(right);

            leftVal = getValue(leftChar);
            rightVal = getValue(rightChar);
            if (leftVal < rightVal){
                sum += rightVal;
                sum -= leftVal;
                left += 2;
                right += 2;
            }else if(leftVal >= rightVal){
                sum += leftVal;
                left++;
                right++;
            }
        }
        // 当出现4 9情况时，运算结束后指针必须移两位
        // 当正常情况下，右指针移一位必等于字符串长度，也有必要必将移动后的左指针对应的数 相加
        if (right == s.length()) { 
            sum += getValue(s.charAt(left));
        }
        return sum;
    }
    
    public static int getValue(char ch){
        
        switch (ch){
            case 'I':return 1;
            case 'V':return 5;
            case 'X':return 10;
            case 'L':return 50;
            case 'C':return 100;
            case 'D':return 500;
            case 'M':return 1000;
        }
        return 0;
    }
}
